package org.utils.annotation;

import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import static org.utils.fp.collection.CollectionFactory.*;

/**
 *
 * @author gus
 */
class AnnatatedClassImpl<A extends Annotation> implements AnnotatedClassInfo<A>
{
    private final Class ownerClass;

    public AnnatatedClassImpl(Class ownerClass)
    {
        this.ownerClass = ownerClass;
    }

    @Override
    public A getAnnotation(Class clazz)
    {
        return (A) ownerClass.getAnnotation(clazz);
    }

    @Override
    public Collection<A> getSummaryAnnotations(Class clazz)
    {
        List<A> list = newArrayList(10);
        recursiveExtract(list, ownerClass, clazz);
        A anno = getAnnotation(clazz);
        if (anno != null)
        {
            list.add(anno);
        }
        return list;
    }

    private void recursiveExtract(List<A> result, Class clazz, Class<A> annotationCLass)
    {
        A annotation = null;
        Class superClass = clazz.getSuperclass();
        if (superClass != null && superClass != Object.class)
        {
            recursiveExtract(result, superClass, annotationCLass);

            if ((annotation = (A) superClass.getAnnotation(annotationCLass)) != null)
            {
                result.add(annotation);
            }
        }

        for (Class interfaceClass : clazz.getInterfaces())
        {
            recursiveExtract(result, interfaceClass, annotationCLass);

            if ((annotation = (A) interfaceClass.getAnnotation(annotationCLass)) != null)
            {
                result.add(annotation);
            }
        }
    }
}
